package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ElectroplatingTankMapper;
import com.bf.electroplating.pojo.dto.tank.ElectroplatingTankDTO;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.ComWorkshop;
import com.bf.electroplating.pojo.entity.ElectroplatingTank;
import com.bf.electroplating.pojo.vo.ActualDataVO;
import com.bf.electroplating.pojo.vo.EnterpriseDataVO;
import com.bf.electroplating.pojo.vo.WorkshopTankDataVO;
import com.bf.electroplating.pojo.vo.tank.ElectroplatingTankVO;
import com.bf.electroplating.pojo.vo.tank.WorkshopTankAreaSummaryVO;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.ComWorkshopService;
import com.bf.electroplating.service.ElectroplatingTankService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.stream.Collectors;
import java.util.List;

@Service
@Slf4j
public class ElectroplatingTankServiceImpl extends ServiceImpl<ElectroplatingTankMapper, ElectroplatingTank>  implements ElectroplatingTankService {

    @Resource
    private ElectroplatingTankMapper electroplatingTankMapper;
    @Resource
    private ComCompanyService comCompanyService;
    @Resource
    private ComWorkshopService comWorkshopService;

    @Override
    public Page<ElectroplatingTankVO> getTankList(ElectroplatingTankDTO dto) {
        Page<ElectroplatingTank> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        
        LambdaQueryWrapper<ElectroplatingTank> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(dto.getEnterpriseName()), ElectroplatingTank::getEnterpriseName, dto.getEnterpriseName())
                   .like(StringUtils.hasText(dto.getWorkshopCode()), ElectroplatingTank::getWorkshopCode, dto.getWorkshopCode())
                   .like(StringUtils.hasText(dto.getWorkshopName()), ElectroplatingTank::getWorkshopName, dto.getWorkshopName())
                   .like(StringUtils.hasText(dto.getTankName()), ElectroplatingTank::getTankName, dto.getTankName())
                   .orderByDesc(ElectroplatingTank::getCreateTime);
        
        Page<ElectroplatingTank> tankPage = electroplatingTankMapper.selectPage(page, queryWrapper);
        
        Page<ElectroplatingTankVO> voPage = new Page<>(tankPage.getCurrent(), tankPage.getSize(), tankPage.getTotal());
        List<ElectroplatingTankVO> voList = tankPage.getRecords().stream()
                .map(tank -> {
                    ElectroplatingTankVO vo = new ElectroplatingTankVO();
                    BeanUtils.copyProperties(tank, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        
        return voPage;
    }

    @Override
    public ElectroplatingTankVO getTankById(Long id) {
        ElectroplatingTank tank = electroplatingTankMapper.selectById(id);
        ElectroplatingTankVO vo = new ElectroplatingTankVO();
        BeanUtils.copyProperties(tank, vo);
        return vo;
    }

    @Override
    public Boolean saveTank(ElectroplatingTankVO vo) {
        ElectroplatingTank tank = new ElectroplatingTank();
        BeanUtils.copyProperties(vo, tank);
        tank.setStatus("1"); // 默认启用状态
        ComWorkshop comWorkshop=comWorkshopService.getById(vo.getWorkshopId());
        if (comWorkshop==null){
            throw new RuntimeException("车间不存在!");
        }
        ComCompany company=comCompanyService.getById(comWorkshop.getCompanyId());
        if (company==null){
            throw new RuntimeException("企业不存在!");
        }
        tank.setEnterpriseId(company.getId());
        tank.setEnterpriseName(company.getCompanyName());
        tank.setParkId("1001");
        return electroplatingTankMapper.insert(tank) > 0;
    }

    @Override
    public Boolean updateTank(ElectroplatingTankVO vo) {
        ElectroplatingTank tank = new ElectroplatingTank();
        BeanUtils.copyProperties(vo, tank);

        return electroplatingTankMapper.updateById(tank) > 0;
    }

    @Override
    public Boolean deleteTank(Long id) {
        return electroplatingTankMapper.deleteById(id) > 0;
    }

    @Override
    public Boolean batchDeleteTank(List<String> ids) {
        return electroplatingTankMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<ElectroplatingTankVO> getTanksByWorkshopId(Long workshopId) {
        LambdaQueryWrapper<ElectroplatingTank> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectroplatingTank::getWorkshopId, workshopId)
                   .orderByDesc(ElectroplatingTank::getCreateTime);
        
        List<ElectroplatingTank> tanks = electroplatingTankMapper.selectList(queryWrapper);
        return tanks.stream()
                .map(tank -> {
                    ElectroplatingTankVO vo = new ElectroplatingTankVO();
                    BeanUtils.copyProperties(tank, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public WorkshopTankDataVO getWorkshopTankData(Long workshopId) {
        log.info("根据车间ID获取车间镀槽数据，车间ID: {}", workshopId);

        // 查询车间下的所有镀槽
        LambdaQueryWrapper<ElectroplatingTank> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectroplatingTank::getWorkshopId, workshopId)
                .orderByAsc(ElectroplatingTank::getTankName);

        List<ElectroplatingTank> tankList = this.list(queryWrapper);

        if (CollectionUtils.isEmpty(tankList)) {
            log.warn("车间ID {} 下没有找到镀槽数据", workshopId);
            return new WorkshopTankDataVO();
        }

        // 构建返回数据
        WorkshopTankDataVO result = new WorkshopTankDataVO();

        // 设置基础信息
        ElectroplatingTank firstTank = tankList.get(0);
        result.setEnterpriseName(firstTank.getEnterpriseName());
        result.setWorkshopCode(firstTank.getWorkshopCode());
        result.setWorkshopName(firstTank.getWorkshopName());
        result.setStatus("1".equals(firstTank.getStatus()) ? "正常" : "停用");

        // 构建企业提供数据
        EnterpriseDataVO enterpriseData = new EnterpriseDataVO();
        List<com.bf.electroplating.pojo.vo.ElectroplatingTankVO> enterpriseTankList = tankList.stream().map(tank -> {
            com.bf.electroplating.pojo.vo.ElectroplatingTankVO vo = new com.bf.electroplating.pojo.vo.ElectroplatingTankVO();
            BeanUtils.copyProperties(tank, vo);
            return vo;
        }).collect(Collectors.toList());
        enterpriseData.setTankList(enterpriseTankList);

        // 计算企业提供数据总容积
        BigDecimal enterpriseTotalVolume = tankList.stream()
                .filter(tank -> tank.getEiaVolume() != null)
                .map(ElectroplatingTank::getEiaVolume)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        enterpriseData.setTotalVolume(enterpriseTotalVolume);

        result.setEnterpriseData(enterpriseData);

        // 构建实测数据
        ActualDataVO actualData = new ActualDataVO();
        List<com.bf.electroplating.pojo.vo.ElectroplatingTankVO> actualTankList = tankList.stream().map(tank -> {
            com.bf.electroplating.pojo.vo.ElectroplatingTankVO vo = new com.bf.electroplating.pojo.vo.ElectroplatingTankVO();
            BeanUtils.copyProperties(tank, vo);
            return vo;
        }).collect(Collectors.toList());
        actualData.setTankList(actualTankList);

        // 计算实测数据总容积
        BigDecimal actualTotalVolume = tankList.stream()
                .filter(tank -> tank.getActualVolume() != null)
                .map(ElectroplatingTank::getActualVolume)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        actualData.setTotalVolume(actualTotalVolume);

        // 设置实测日期（取最新更新时间）
        if (!CollectionUtils.isEmpty(tankList)) {
            String measureDate = tankList.stream()
                    .filter(tank -> tank.getUpdateTime() != null)
                    .map(tank -> {
                        SimpleDateFormat formatter = new SimpleDateFormat("MM.dd");
                        String temp = formatter.format(tank.getUpdateTime());
                        return temp;
                    })
                    .findFirst()
                    .orElse("");
            actualData.setMeasureDate(measureDate);
        }

        result.setActualData(actualData);

        log.info("成功获取车间ID {} 的镀槽数据，共 {} 个镀槽", workshopId, tankList.size());
        return result;
    }

    @Override
    public WorkshopTankAreaSummaryVO getWorkshopTankAreaSummary(Long workshopId) {
        log.info("根据车间ID获取车间镀槽面积汇总，车间ID: {}", workshopId);

        // 查询车间下的所有镀槽
        LambdaQueryWrapper<ElectroplatingTank> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectroplatingTank::getWorkshopId, workshopId)
                .eq(ElectroplatingTank::getStatus, "1")
                .orderByAsc(ElectroplatingTank::getTankName);

        List<ElectroplatingTank> tankList = this.list(queryWrapper);

        if (CollectionUtils.isEmpty(tankList)) {
            log.warn("车间ID {} 下没有找到镀槽数据", workshopId);
            return new WorkshopTankAreaSummaryVO();
        }

        // 构建返回数据
        WorkshopTankAreaSummaryVO result = new WorkshopTankAreaSummaryVO();

        // 设置基础信息
        ElectroplatingTank firstTank = tankList.get(0);
        result.setEnterpriseName(firstTank.getEnterpriseName());
        result.setWorkshopCode(firstTank.getWorkshopCode());
        result.setWorkshopName(firstTank.getWorkshopName());
        result.setStatus("1".equals(firstTank.getStatus()) ? "正常" : "停用");
        result.setTotalTankCount(tankList.size());

        // 计算上报总面积之和（环评数据：长 × 宽 × 数量）
        BigDecimal reportedTotalArea = tankList.stream()
                .filter(tank -> tank.getEiaLength() != null && tank.getEiaWidth() != null && tank.getEiaQuantity() != null)
                .map(tank -> {
                    BigDecimal area = tank.getEiaLength().multiply(tank.getEiaWidth());
                    return area.multiply(BigDecimal.valueOf(tank.getEiaQuantity()));
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 计算实际测量总面积之和（实测数据：长 × 宽 × 数量）
        BigDecimal actualTotalArea = tankList.stream()
                .filter(tank -> tank.getActualLength() != null && tank.getActualWidth() != null && tank.getActualQuantity() != null)
                .map(tank -> {
                    BigDecimal area = tank.getActualLength().multiply(tank.getActualWidth());
                    return area.multiply(BigDecimal.valueOf(tank.getActualQuantity()));
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        result.setReportedTotalArea(reportedTotalArea);
        result.setActualTotalArea(actualTotalArea);

        // 构建上报数据镀槽列表
        List<ElectroplatingTankVO> reportedTankList = tankList.stream()
                .map(tank -> {
                    ElectroplatingTankVO vo = new ElectroplatingTankVO();
                    BeanUtils.copyProperties(tank, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        result.setReportedTankList(reportedTankList);

        // 构建实测数据镀槽列表
        List<ElectroplatingTankVO> actualTankList = tankList.stream()
                .map(tank -> {
                    ElectroplatingTankVO vo = new ElectroplatingTankVO();
                    BeanUtils.copyProperties(tank, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        result.setActualTankList(actualTankList);

        // 计算面积差异
        BigDecimal areaDifference = actualTotalArea.subtract(reportedTotalArea);
        result.setAreaDifference(areaDifference);

        // 计算面积差异百分比
        BigDecimal areaDifferencePercent = BigDecimal.ZERO;
        if (reportedTotalArea.compareTo(BigDecimal.ZERO) > 0) {
            areaDifferencePercent = areaDifference.divide(reportedTotalArea, 4, java.math.RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
        }
        result.setAreaDifferencePercent(areaDifferencePercent);

        log.info("成功获取车间ID {} 的镀槽面积汇总，上报总面积: {} m²，实际总面积: {} m²，差异: {} m² ({}%)", 
                workshopId, reportedTotalArea, actualTotalArea, areaDifference, areaDifferencePercent);
        
        return result;
    }
}